﻿using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using PMS.SANY.Entity;
using Microsoft.Extensions.Logging;

namespace PMS.SANY.Api
{
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
    public class TransactionAttribute : Attribute, IAsyncActionFilter
    {
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<TransactionAttribute>>();
            var dbContext = context.HttpContext.RequestServices.GetRequiredService<GDbContext>();
            var tran = await dbContext.Database.BeginTransactionAsync();
            logger.LogInformation("事务开始：Begin Transaction Async");
            var nextContext = await next();
            if (nextContext.Exception != null)
            {
                await tran.RollbackAsync();
                logger.LogError("事务回退：Transaction Rollback Async");
            }
            else
            {
                await tran.CommitAsync();
                logger.LogInformation("事务提交：Transaction Commit Async");
            }
        }
    }
}
